package com.sxyc.utils;

import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;

/**
 * 百度地图工具类
 * @author WangQian
 *
 */
public class BaiduMapUtils {

	// 使用jFinal 日志
	private static com.jfinal.log.Log log = com.jfinal.log.Log.getLog(BaiduMapUtils.class);

	private static String ak = "EqQnCSF1t49Ba2cmKV8MPEI3c1hiynU8";

	private static String sk = "u71V47Q97y75ECWGuj61XQIa1OlfPcdz";

	private static String rootUrl = "http://api.map.baidu.com";

	public static Map<String, String> _paramsMap = new LinkedHashMap<String, String>();
	
	BaiduMapUtils(){
		_paramsMap.clear();
	}
	
	/**
	 * 获得SN码
	 * @param url
	 * @param paramsMap
	 * @return
	 */
	private static String getSN(String url, Map<String, String> paramsMap) {
		String sn = "";
		try {
			if (paramsMap == null) {
				paramsMap = _paramsMap;
			}
			// 如果参数中有ak，则移除重新添加
			if (paramsMap.containsKey("ak")) {
				paramsMap.remove("ak");
			}
			paramsMap.put("ak", ak);
			if (paramsMap.containsKey("output")) {
				paramsMap.remove("output");
			}
			paramsMap.put("output", "json");
			String paramsStr = toQueryString(paramsMap);
			String wholeStr = new String(url + "?" + paramsStr + sk);
			String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
			sn = MD5(tempStr);
		} catch (Exception e) {
			log.error("getSN Exception ：" + e.getMessage());
		}
		return sn;
	}

	/**
	 * 将Map参数转换为String参数
	 * @param data
	 * @return
	 */
	private static String toQueryString(Map<?, ?> paramsMap) {
		StringBuffer queryString = new StringBuffer();
		try {
			for (Entry<?, ?> pair : paramsMap.entrySet()) {
				queryString.append(pair.getKey() + "=");
				queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
			}
			if (queryString.length() > 0) {
				queryString.deleteCharAt(queryString.length() - 1);
			}
		} catch (Exception e) {
			log.error("toQueryString Exception ：" + e.getMessage());
		}
		return queryString.toString();
	}

	/**
	 * MD5加密
	 * @param md5
	 * @return
	 */
	private static String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (Exception e) {
			log.error("MD5 Exception ：" + e.getMessage());
		}
		return null;
	}

	/**
	 * 百度API请求方法
	 * @param url 请求地址,如：/geocoder/v2/
	 * @param paramsMap 请求参数，忽略：ak、output（默认为：json）
	 * @return
	 */
	public static String getResult(String url, Map<String, String> paramsMap) {
		String result = "";
		try {
			if (paramsMap == null) {
				paramsMap = _paramsMap;
			}
			// 如果参数中有ak，则移除重新添加
			if (paramsMap.containsKey("ak")) {
				paramsMap.remove("ak");
			}
			paramsMap.put("ak", ak);
			if (paramsMap.containsKey("output")) {
				paramsMap.remove("output");
			}
			paramsMap.put("output", "json");
			String sn = getSN(url, paramsMap);
			String requestUrl = rootUrl + url + "?" + toQueryString(paramsMap) + "&sn=" + sn;
			result = HttpKit.get(requestUrl);
			log.info("url = "+url);
			log.info("paramsMap = "+toQueryString(paramsMap));
			log.info("result = "+result);
			log.info(result);
		} catch (Exception e) {
			log.error("getResult Exception ：" + e.getMessage());
		}
		return result;
	}

	/**
	 * 根据经纬度获取地址信息
	 * @param lat 纬度
	 * @param lng 经度
	 * @return
	 */
	public static String getAddress(double lat, double lng) {
		String address = "";
		try {
			String url = "/geocoder/v2/";
			//Map paramsMap = new LinkedHashMap<String, String>();
			_paramsMap.clear();
			_paramsMap.put("location", lat + "," + lng);
			_paramsMap.put("output", "json");
			String result = getResult(url, _paramsMap);
			if (result != null) {
				JSONObject data = JSONObject.parseObject(result);
				String status = data.getString("status");
				if ("0".equals(status)) {
					JSONObject resultData = (JSONObject) data.get("result");
					if(resultData!=null){
						address = resultData.getString("formatted_address");
					}
				} else {
					String message = data.getString("message");
					log.error("getAddress 失败！错误代码：" + result + ";错误消息：" + message);
				}
			}
		} catch (Exception e) {
			log.error("getAddress Exception：" + e.getMessage());
		}
		return address;
	}

	public static void main(String[] args) {
		//获取西安市钟楼（东西南北四条大街交汇处）地址
		String result = BaiduMapUtils.getAddress(34.265678, 108.953382);
		System.out.println(result);
	}
}
